/*
 * @(#)XmlMarshaller.java   2015.五月.14 03:55 下午
 * 
 * Copyright (c) 2015 www.7jia2.com
 *
 * 版权声明： 版权所有 违者必究 2015
 *
 */

package com.oaf.response;

//~--- non-JDK imports --------------------------------------------------------

import com.oaf.exception.OafException;

//~--- JDK imports ------------------------------------------------------------

import java.io.OutputStream;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 * @ClassName: XmlMarshaller    
 * @Description:Xml格式的流化
 * @Date:2015.五月.14 03:55 下午
 * @version        0.8, 2015.五月.14 03:55 下午
 * @author         xu.wengang@7jia2.com  
 */
public class XmlMarshaller implements OafMarshaller {
    /**容器*/
    private Map<Class, JAXBContext> xmlMap = new ConcurrentHashMap<Class, JAXBContext>();

    /**
     * @Title:marshaller
     * @Description:
     * @param object
     * @param outputStream
     */
    @Override
    public void marshaller(Object object, OutputStream outputStream){
        try {
            Marshaller marshaller = buildMarshaller(object.getClass());

            marshaller.marshal(object, outputStream);
        } catch (JAXBException e) {
            throw new OafException(e);
        }
    }

    /**
     * @Title:buildMarshaller
     * @Description:
     * @param objectType
     * @return
     * @throws JAXBException
     */
    private Marshaller buildMarshaller(Class<?> objectType) throws JAXBException{
        if (!xmlMap.containsKey(objectType)) {
            JAXBContext jaxbContext = JAXBContext.newInstance(objectType);

            xmlMap.put(objectType, jaxbContext);
        }

        JAXBContext context    = xmlMap.get(objectType);
        Marshaller  marshaller = context.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");

        return marshaller;
    }
}

